﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using BayatGames.SaveGameFree;
using UnityEngine.EventSystems;

public class GameUtils
{
    class CustomData
    {
        public string data;

        public CustomData(string text)
        {
            data = text;
        }
    }

    static public byte[] ReadFileAsBytes(string filePath)
    {
        if (!File.Exists(filePath))
        {
            return null;
        }
        try
        {
            File.SetAttributes(filePath, FileAttributes.Normal);
            return File.ReadAllBytes(filePath);
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.LogError(ex.Message);
            return null;
        }
    }

    static public string ReadFileText(string filePath)
    {
        if(SaveGame.Exists(filePath, SaveGamePath.PersistentDataPath))
        {
            var data = SaveGame.Load<CustomData>(filePath, SaveGamePath.PersistentDataPath);
            return data.data;
        }
        return "";
    }

    static public void WriteFileText(string filePath,string text)
    {
        CustomData data = new CustomData(text);
        SaveGame.Save<CustomData>(filePath, data, SaveGamePath.PersistentDataPath);
    }

    static public Vector2 convertWorldPosToUIPos(Camera uicamera, Vector3 worldPos, RectTransform rect)
    {
        var sceenPos = RectTransformUtility.WorldToScreenPoint(Camera.main, worldPos);
        var outPos = new Vector2();
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rect, sceenPos, uicamera, out outPos);
        return outPos;
    }

    static public Vector2 convertScreenPointToUIPos(Camera uicamera,Vector2 screenPoint,RectTransform rect)
    {
        var outPos = new Vector2();
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rect, screenPoint, uicamera, out outPos);
        return outPos;
    }

    static public bool IsNull(UnityEngine.Object target)
    {
        return target == null;
    }

    /// <summary>
    /// 点击屏幕坐标
    /// </summary>
    /// <param name="position"></param>
    /// <returns></returns>
    static public GameObject GetFirstPickGameObject(Vector2 position)
    {
        EventSystem eventSystem = EventSystem.current;
        PointerEventData pointerEventData = new PointerEventData(eventSystem);
        pointerEventData.position = position;
        //射线检测ui
        List<RaycastResult> uiRaycastResultCache = new List<RaycastResult>();
        eventSystem.RaycastAll(pointerEventData, uiRaycastResultCache);
        if (uiRaycastResultCache.Count > 0)
            return uiRaycastResultCache[0].gameObject;
        return null;
    }
}
